<?php

namespace app\nideshop\controller;

use think\Db;
use app\nideshop\validate\CartValidate;
use app\nideshop\service\Token;

class Cart extends Base
{
	/**
	 * 接收请求参数
	 * @var [type]
	 */
	protected $datas;

	/**
	 * 对应数据表
	 * @var string
	 */
	protected $table = 'cart';

	/**
	 * 获取购物车的数据
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-23T19:50:32+0800
	 * @return   [type]                   [description]
	 */
	protected function _getCart($userId)
	{
		$cartList = Db::name($this->table)->where(['user_id' => $userId, 'session_id' => 1])->select();
		$goodsCount = 0;
      	$goodsAmount = 0.00;
      	$checkedGoodsCount = 0;
      	$checkedGoodsAmount = 0.00;
      	foreach ($cartList as $key => $value) {
      		$goodsCount += $value['number'];
      		$goodsAmount += $value['number'] * $value['retail_price'];
      		if (!empty($value['checked'])) {
      			$checkedGoodsCount += $value['number'];
      			$checkedGoodsAmount += $value['number'] * $value['retail_price'];
      		}
      		$value['list_pic_url'] = Db::name('goods')->where('id', $value['goods_id'])->value('list_pic_url');
      	}
      	return [
      		'cartList' => $cartList,
  			'cartTotal' => [
  				'goodsCount' => $goodsCount,
  				'goodsAmount' =>$goodsAmount,
  				'checkedGoodsCount' => $checkedGoodsCount,
  				'checkedGoodsAmount' => $checkedGoodsAmount
  			]
      	];
	}

	/**
	 * 购物车的数据
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-23T19:52:07+0800
	 * @return   [type]                   [description]
	 */
	public function indexAction()
	{
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$data = $this->_getCart($userId);
      	return json([
      		'errno' => 0,
      		'errmsg' => '',
      		'data' => $data
      	]);
	}

	/**
	 * 添加商品到购物车
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-23T19:39:13+0800
	 */
	public function addAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new CartValidate, 'add', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'msg' => $valiResult, 'data' => []]);
		}
		$goodsId = $this->datas['goodsId'];
		$productId = $this->datas['productId'];
		$number = $this->datas['number'];
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
      	$goodsInfo = Db::name('goods')->where('id', $goodsId)->find();
      	if (empty($goodsInfo) || $goodsInfo['is_delete'] === 1) {
      		return json(['errno' => 400, 'errmsg' => '商品已下架', 'data' => []]);
      	}
      	$productInfo = Db::name('product')->where(['goods_id' => $goodsId, 'id' => $productId])->find();
      	if (empty($productInfo) || $productInfo['goods_number'] < $number) {
      		return json(['errno' => 400, 'errmsg' => '库存不足', 'data' => []]);
      	}
      	$cartInfo = Db::name($this->table)->where(['goods_id' => $goodsId, 'product_id' => $productId])->find();
      	if (empty($cartInfo)) {
      		// 添加规格名和值
	        $goodsSepcifitionValue = [];
	        if (!empty($productInfo['goods_specification_ids'])) {
	        	$goodsSepcifitionValue = Db::name('goods_specification')
	        		->where('goods_id', $goodsId)
	        		->whereIn('id', explode('_', $productInfo['goods_specification_ids']))
	        		->column('value');
	        }
      		$cartData = [
				'goods_id' => $goodsId,
				'product_id' => $productId,
				'goods_sn' => $productInfo['goods_sn'],
				'goods_name' => $goodsInfo['name'],
				'list_pic_url' => $goodsInfo['list_pic_url'],
				'number' => $number,
				'session_id' => 1,
				'user_id' => $userId,
				'retail_price' => $productInfo['retail_price'],
				'market_price' => $productInfo['retail_price'],
				'goods_specifition_name_value' => implode(';', $goodsSepcifitionValue),
				'goods_specifition_ids' => $productInfo['goods_specification_ids'],
				'checked' => 1,
				//'create_time' => time()
        	];
        	$result = Db::name($this->table)->insert($cartData);
      	} else {
      		if ($productInfo['goods_number'] < $number + $cartInfo['number']) {
	          	return json(['errno' => 400, 'errmsg' => '库存不足', 'data' => []]);
	        }
        	$result = Db::name($this->table)
        		->where([
	        		'goods_id' => $goodsId,
	        		'product_id' => $productId,
	        		'id' => $cartInfo['id']
        		])
        		->inc('number', $number);
        		//->update(['update_time' => time()]);
      	}
      	if (!$result) {
      		return json(['errno' => 400, 'errmsg' => '添加失败', 'data' => []]);
      	}
      	$list = $this->_getCart($userId);
      	return json(['errno' => 0, 'errmsg' => '', 'data' => $list]);
	}
	
	/**
	 * 修改购物车内商品
	 * @Author   Yichen
	 * @DateTime 2020-05-23T20:24:55+0800
	 * @return   [type]                   [description]
	 */
	public function updateAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new CartValidate, 'update', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'errmsg' => $valiResult, 'data' => []]);
		}
		$goodsId = $this->datas['goodsId'];
		$id = $this->datas['id'];
		$number = $this->datas['number'];
		$productId = $this->datas['productId'];
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
      	// 取得规格的信息,判断规格库存
      	$productInfo = Db::name('product')->where(['goods_id' => $goodsId, 'id' => $productId])->find();
      	if (empty($productInfo) || $productInfo['goods_number'] < $number) {
        	return json(['errno' => 400, 'errmsg' => '库存不足', 'data' => []]);
     	}
     	$cartInfo = Db::name($this->table)->where('id', $id)->find();
     	if (empty($cartInfo)) {
     		return json(['errno' => 400, 'errmsg' => '修改失败', 'data' => []]);
     	}
     	$result = Db::name($this->table)
     		->where('id', $id)
     		->update(['number' => $number/*, 'update_time' => time()*/]);
 		if (!$result) {
 			return json(['errno' => 400, 'errmsg' => '修改失败', 'data' => []]);
 		}
 		$list = $this->_getCart($userId);
 		return json([
 			'errno' => 0,
 			'errmsg' => '', 
 			'data' => $list
 		]);
	}

	/**
	 * 删除购物车商品
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-24T10:35:28+0800
	 * @return   [type]                   [description]
	 */
	public function deleteAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new CartValidate, 'del', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'msg' => $valiResult, 'data' => []]);
		}
		$productIds = $this->datas['productIds'];
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$productIdArr = explode(',', $productIds);
		$result = Db::name($this->table)->whereIn('product_id', $productIdArr)->delete();
		if (!$result) {
			return json(['errno' => 400, 'errmsg' => '删除失败', 'data' => []]);
		}
		$list = $this->_getCart($userId);
		return json([
			'errno' => '',
			'errmsg' => '删除成功',
			'data' => $list
		]);
	} 

	/**
	 * 获取购物车商品的总件件数
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-23T11:50:47+0800
	 * @return   [type]                   [description]
	 */
	public function goodscountAction()
	{
		$userId = 0;
		$total = 0;
		if (!empty($_SERVER['HTTP_X_NIDESHOP_TOKEN'])) {
			$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
			$cartData = Db::name($this->table)
				->where(['user_id' => $userId, 'session_id' => 1])
				->column('number');
			$total = array_sum($cartData);
		} 
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => [
				'cartTotal' => [
					'goodsCount' => $total
				]
			]
		]);
	}
	
	/**
	 * 选择或取消选择商品
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-24T22:06:50+0800
	 * @return   [type]                   [description]
	 */
	public function checkedAction()
	{
		$this->datas = $this->params;
		$valiResult = $this->checkParam(new CartValidate, 'check', $this->datas);
		if ($valiResult !== true) {
			return json(['errno' => 400, 'msg' => $valiResult, 'data' => []]);
		}
		$productIds = $this->datas['productIds'];
		$isChecked = $this->datas['isChecked'];
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$productIdArr = explode(',', $productIds);
		$result = Db::name($this->table)->whereIn('product_id', $productIdArr)->update(['checked' => $isChecked]);
		if (!$result) {
			return json(['errno' => '400', 'errmsg' => '失败', 'data' => []]);
		}
		$list = $this->_getCart($userId);
		return json([
			'errno' => 0,
			'errmsg' => '',
			'data' => $list
		]);
	}

	/**
	 * 下单前信息确认
	 * @Author   fanzhongxing
	 * @DateTime 2020-05-24T22:51:55+0800
	 * @return   [type]                   [description]
	 */
	public function checkoutAction()
	{
		$this->datas = $this->params;
		$addressId = isset($this->datas['addressId']) ? $this->datas['addressId'] : '';
		$userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);
		$checkedAddress = '';
		if ($addressId) {
			$checkedAddress = Db::name('address')->where(['is_default' => 1, 'user_id' => $userId])->find();
		} else {
			$checkedAddress = Db::name('address')->where(['id' => $addressId, 'user_id' => $userId])->find();
		}
		if (!empty($checkedAddress)) {
	    	$checkedAddress['province_name'] = Db::name('region')
	    		->where('id', $checkedAddress['province_id'])
	    		->value('name');
	    	$checkedAddress['city_name'] = Db::name('region')
	    		->where('id', $checkedAddress['city_id'])
	    		->value('name');
	    	$checkedAddress['district_name'] = Db::name('region')
	    		->where('id', $checkedAddress['district_id'])
	    		->value('name');
	    	$checkedAddress['full_region'] = $checkedAddress['province_name'] . $checkedAddress['city_name'] . $checkedAddress['district_name'];	
		}
		// 根据收货地址计算运费
    	$freightPrice = 0.00;
    	// 获取要购买的商品
    	$cartData = $this->_getCart($userId);
    	$checkedGoodsList = $cartData['cartList'];
    	foreach ($checkedGoodsList as $key => $value) {
    		$checkedGoodsList[$key]['checked'] = 1;
    	}
    	// 获取可用的优惠券信息，功能还示实现
    	$couponList = Db::name('user_coupon')->select();
    	$couponPrice = 0.00; // 使用优惠券减免的金额
    	// 计算订单的费用
	    $goodsTotalPrice = $cartData['cartTotal']['checkedGoodsAmount']; // 商品总价
	    $orderTotalPrice = ($cartData['cartTotal']['checkedGoodsAmount']) + $freightPrice - $couponPrice; // 订单的总价
	    $actualPrice = $orderTotalPrice - 0.00; // 减去其它支付的金额后，要实际支付的金额
	    return json([
	    	'errno' => 0,
	    	'errmsg' => '',
	    	'data' => [
	    		'checkedAddress' => $checkedAddress,
	    		'freightPrice' => $freightPrice,
	    		'checkedCoupon' => (object)[],
	    		'couponList' => $couponList,
	    		'couponPrice' => $couponPrice,
	    		'checkedGoodsList' => $checkedGoodsList,
	    		'goodsTotalPrice' => $goodsTotalPrice,
	    		'orderTotalPrice' => $orderTotalPrice,
	    		'actualPrice' => $actualPrice
	    	]
	    ]);
	}
}